package com.atguigu.flink.streamapi.transform;

import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created by Smexy on 2022/11/21
 *
 *  先keyBy，才能reduce
 *  Reduce: 两两聚合。  每两个元素聚合一次。
 *          滚动聚合。  输入一条，满足条件，调用一次
 */
public class Demo7_Reduce
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           //统计所有传感器的累积水位和 vc
           .keyBy(w -> "a")
           .reduce(new ReduceFunction<WaterSensor>()
           {
               /*
                    reduce的特点是，输入和输出的类型必须一致！
                        value1: 是累积的最新的结果
                        value2: 当前要累加的元素
                */
               @Override
               public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                   System.out.println("Demo7_Reduce.reduce");
                   value2.setVc(value1.getVc() + value2.getVc());
                   return value2;
               }
           })
           .print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
